<template>
  <div class="pintuan-goods">
    <a-card :bordered="false">
      <tablePage
        :columns="columns"
        :data-list="data"
        :enable-pagination="false"
        :bordered="true"
      ></tablePage>
      <a-divider orientation="left" v-if="data[0] && data[0].pintuanRule">拼团规则</a-divider>
      <div v-if="data[0] && data[0].pintuanRule" style="margin-bottom: 30px;">{{data[0].pintuanRule}}</div>
      <a-col v-if="status === 'manager'" :span="16" style="margin: 30px 0">
        <s-space>
          <a-button
            style="margin-right: 10px"
            type="outline"
            @click="openSkuList"
          >
            选择商品
          </a-button>
          <a-button type="outline" status="danger" @click="delAll"
            >批量删除</a-button
          >
        </s-space>
      </a-col>
      <a-divider orientation="left">活动商品</a-divider>
      <tablePage
        :columns="goodsColumns"
        :data-list="goodsData"
        :checkbox="true"
        :methods="sortMethods"
        :bordered="true"
        :default-selected-keys="selectedKeys"
        :enable-pagination="false"
        @selectionChanges="
          (val) => {
            selectedKeys = val;
          }
        "
      >
        <template #pintuanPrice="{ data, rowIndex }">
          <a-input-number
            v-model="data.price"
            :disabled="status == 'view'"
            :min="1"
            :max="999999999"
            @input="goodsData[rowIndex].price = data.price"
          ></a-input-number>
        </template>
        <template #delete="{ rowIndex }">
          <a-button
            v-if="status === 'manager'"
            type="text"
            status="danger"
            @click="delGoods(rowIndex)"
            >删除</a-button
          >
        </template>
      </tablePage>
      <a-col :span="16" style="margin: 30px 0">
        <a-button style="margin-right: 5px" @click="closeCurrentPage"
          >返回</a-button
        >
        <a-button
          v-if="status == 'manager'"
          type="primary"
          @click="handleSubmit"
          >保存</a-button
        >
      </a-col>
    </a-card>
    <skuselect
      ref="skuSelect"
      :goods-or-sku="true"
      :default-goods-selected-list="goodsData"
      :api-params="apiParam"
      @change="changSkuList"
    />
  </div>
</template>

<script lang="ts" setup>
  import { ref, onMounted } from 'vue';
  import tablePage from '@/components/table-pages/index.vue';
  import skuselect from '@/components/goods-sku-selector/index.vue';
  import { ColumnsDataRule, MethodsRule } from '@/types/global';
  import { promotionStatus } from '@/utils/tools';
  import { editPintuan, getPintuanDetail } from '@/api/promotion';
  import { useRoute, useRouter } from 'vue-router';
  import { Message } from '@arco-design/web-vue';
  import useCurrentInstance from '@/hooks/useCurrentInstance';

  const route = useRoute();
  const router = useRouter();
  // 传递的参数
  const apiParam = {
    marketEnable: 'UPPER',
    authFlag: 'PASS',
    salesModel: 'RETAIL',
  };
  const data = ref<Array<any>>([]);
  const goodsData = ref<Array<any>>([]);
  const status = ref<any>();
  const skuSelect = ref(null) as any; // 商品选择器
  const promotionGoodsList = ref([]) as any; // 活动商品列表
  const selectedGoods = ref([]); // 已选商品列表，便于删除
  //  获取modal
  const modal = useCurrentInstance().globalProperties?.$modal;
  // 多选数据
  const selectList = ref([]); // 接受子组件传过来的值
  const selectedKeys = ref([]);
  const columns: ColumnsDataRule[] = [
    {
      title: '活动名称',
      dataIndex: 'promotionName',
    },
    {
      title: '活动开始时间',
      dataIndex: 'startTime',
    },
    {
      title: '活动结束时间',
      dataIndex: 'endTime',
    },
    {
      title: '活动状态',
      dataIndex: 'promotionStatus',
      slot: true,
      slotData: {
        badge: promotionStatus,
      },
    },
    {
      title: '拼团规则',
      dataIndex: 'pintuanRule'
    }
  ];

  const goodsColumns: ColumnsDataRule[] = [
    {
      title: '商品名称',
      dataIndex: 'goodsName',
    },
    {
      title: '库存',
      dataIndex: 'quantity',
    },
    {
      title: '拼团价格',
      dataIndex: 'price',
      slot: true,
      slotTemplate: 'pintuanPrice',
    },
  ];

  const sortMethods: MethodsRule = {
    title: '操作',
    width: 250,
    fixed: 'right',
    methods: [
      {
        title: '删除',
        callback: 'delete',
        slot: true,
        slotTemplate: 'delete',
      },
    ],
  };

  // 选择商品
  const openSkuList = () => {
    skuSelect.value.modalData.visible = true;
  };
  // 选择的商品
  const changSkuList = (val: any) => {
    const list: any = [];
    val.forEach((e: any) => {
      const obj = {
        settlementPrice: e.settlementPrice || 0,
        pointsGoodsCategoryId: e.pointsGoodsCategoryId || 0,
        pointsGoodsCategoryName: e.pointsGoodsCategoryName || '',
        activeStock: e.activeStock || 0,
        points: e.points || 0,
        skuId: e.id,
        goodsId: e.goodsId,
        originalPrice: e.price || 0,
        thumbnail: e.thumbnail || '',
        goodsName: e.goodsName || '',
        quantity: e.quantity || '',
        storeName: e.storeName || '',
        price: e.price || '',
        id: e.id,
      };
      list.push(obj);
    });
    goodsData.value = list;
  };

  // 返回上一页
  const routerpreviousPage = () => {
    router.push({ name: 'pintuan' });
  };
  // 返回
  const closeCurrentPage = () => {
    routerpreviousPage();
  };
  const getDataList = () => {
    getPintuanDetail(route.query.id).then((res) => {
      if (res.data.result) {
        data.value = [] as any;
        data.value.push({
          ...res.data.result,
        });
        goodsData.value = res.data.result.promotionGoodsList;
      }
    });
  };
  // 删除
  const remove = (data: any) => {};
  // 保存
  const handleSubmit = () => {
    if (goodsData.value.length == 0) {
      Message.warning('请选择活动商品');
      return;
    }
    // goodsData.value.forEach((item: any) => {
    //     if(!item.paice){
    //         // Message.error(`请填写【${item.goodsName}】的价格`)
    //         modal.confirm({
    //             title:'提示',
    //             content:`请填写【${item.goodsName}】的价格`
    //         })
    //         return;
    //     }

    // })
    goodsData.value.forEach((item: any) => {
      item.promotionId = data.value[0].id;
      item.startTime = data.value[0].startTime;
      item.endTime = data.value[0].endTime;
    });
    data.value[0].promotionGoodsList = goodsData.value;
    editPintuan(data.value[0]).then((res) => {
      if (res.data.success) {
        Message.success('修改拼团商品成功');
        closeCurrentPage();
      }
    });
  };
  // 删除商品
  const delGoods = (index: any) => {
    goodsData.value.splice(index, 1);
  };

  // 批量删除
  const delAll = () => {
    if (selectedKeys.value.length === 0) {
      Message.warning('您还未选择要删除的数据！');
      return;
    }
    const res = JSON.parse(JSON.stringify(selectedKeys.value));

    modal.confirm({
      title: '确认删除',
      content: '您确认要删除所选商品吗?',
      alignCenter: false,
      onOk: () => {
        goodsData.value = goodsData.value.filter((item: any) => {
          return !res.includes(item.skuId);
        });
        selectedKeys.value = [];
      },
    });
  };

  onMounted(() => {
    getDataList();
    status.value = route.query.status;
  });
</script>
